package com.ls.task;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.config.redis.RedisClient;
import com.ls.constant.SystemConstants;
import com.ls.entity.*;
import com.ls.enums.RoleEnum;
import com.ls.mapper.OrderRecordMapper;
import com.ls.mapper.ScoreRecordMapper;
import com.ls.service.*;
import com.ls.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ls.constant.SystemConstants.*;
import static com.ls.constant.SystemConstants.MEMBER_STATUS_TRUE;
import static com.ls.enums.OrderRecordEnum.getOrderRecordEnum;

/**
 * 支付结果轮询
 */
@Slf4j
@Component
public class PayStatusTask extends ServiceImpl<OrderRecordMapper, OrderRecord> {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private IAlipayPayService alipayPayService;
    @Autowired
    private IWeixinPayService weixinPayService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IOrderRecordService orderRecordService;
    @Autowired
    private ScoreRecordMapper scoreRecordMapper;
    @Value("${pay.close.time}")
    private Integer time;

    @Scheduled(cron = "${schedule.pay.cron}")
    public void payStatusTask() {
        // 查询所有未完成订单并且order_number为null
        List<OrderRecord> orderRecordList = list(new LambdaQueryWrapper<OrderRecord>()
                .eq(OrderRecord::getOrderStatus, PAY_STATUS_WAIT)
                .and(wrapper -> wrapper
                        .isNull(OrderRecord::getThirdOrderNumber)
                        .or()
                        .eq(OrderRecord::getThirdOrderNumber, "")
                )
        );
        if (orderRecordList == null || orderRecordList.size() == 0 || orderRecordList.isEmpty()) {
            return;
        }
        orderRecordList.forEach(orderRecord -> {
            LocalDateTime createTime = orderRecord.getCreateTime();
            LocalDateTime now = LocalDateTime.now();
            // 检查订单创建时间是否在当前时间的3秒之内
            boolean isWithinSeconds = createTime.isAfter(now.minusSeconds(3)) && createTime.isBefore(now);
            //创建10秒内不轮询
            if (isWithinSeconds) {
                return;
            }
            //检查是否过期
            boolean isBeforeMinutes = createTime.isBefore(now.minusMinutes(time));
            if (orderRecord.getPayType() == 1) {
                if (isBeforeMinutes) {
                    weixinPayService.closeOrder(orderRecord.getOrderNum());
                    return;
                } else {
                    String data = weixinPayService.getTaskPayStatus(orderRecord.getOrderNum());
                    if ("false".equals(data) || data == null) {
                        return;
                    }
                    change(orderRecord.getOrderNum(), data);
                }
            } else {
                if (isBeforeMinutes) {
                    alipayPayService.closeOrder(orderRecord.getOrderNum());
                    return;
                } else {
                    String data = alipayPayService.getTaskPayStatus(orderRecord.getOrderNum());
                    if ("false".equals(data) || data == null) {
                        return;
                    }
                    change(orderRecord.getOrderNum(), data);
                }
            }
        });
    }
    public void change(String orderNum, String orderNumber) {
        LocalDateTime dbTime = LocalDateTime.now();
        ResultData resultData = orderRecordService.changeOrder(orderNum,orderNumber,dbTime);
        if (resultData.isSuccess()) {
            Map<String, Object> resultMap = (Map<String, Object>) resultData.getData();
            Boolean isOk = (Boolean) resultMap.get("isOk");
            if (isOk){
                Long customerId = Long.parseLong(resultMap.get("customerId").toString());
                Long productId = Long.parseLong(resultMap.get("productId").toString());
                Long orderRecordId=Long.parseLong(resultMap.get("orderRecordId").toString());
                customerService.changeCustomer(customerId,productId,orderRecordId);
            }
        }
    }
}
